<template>
  <div id="userManagePage">
    <!-- 搜索表单 -->
    <a-form ref="formRef" layout="inline" :model="searchParams" @finish="doSearch">
      <a-form-item label="账号" name="userAccount">
        <a-input v-model:value="searchParams.userAccount" placeholder="输入账号" allow-clear />
      </a-form-item>
      <a-form-item label="用户名" name="userName">
        <a-input v-model:value="searchParams.userName" placeholder="输入用户名" allow-clear />
      </a-form-item>
      <a-form-item>
        <a-space>
          <a-button type="primary" @click="resetSearch">重置</a-button>
          <a-button type="primary" html-type="submit">搜索</a-button>
        </a-space>

      </a-form-item>
    </a-form>
    <div style="margin-bottom: 16px"></div>
    <!-- 表格 -->
    <a-table
      :columns="columns"
      :data-source="dataList"
      :pagination="pagination"
      @change="doTableChange"
    >
      <template #bodyCell="{ column, record, text }">
        <template v-if="column.dataIndex === 'userAvatar'">
          <a-image :src="record.userAvatar" width="120px" />
        </template>
        <template v-else-if="column.dataIndex === 'userRole'">
          <div v-if="record.userRole === 'admin'">
            <a-tag color="green">管理员</a-tag>
          </div>
          <div v-else>
            <a-tag color="blue">普通用户</a-tag>
          </div>
        </template>
        <template v-if="column.dataIndex === 'createTime'">
          {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-if="column.dataIndex === 'updateTime'">
          {{ dayjs(record.updateTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-if="column.dataIndex === 'userName'">
          <div class="editable-cell">
            <div v-if="editableData[record.key]" class="editable-cell-input-wrapper">
              <a-input
                v-model:value="editableData[record.key].userName"
                @pressEnter="save(record.key)"
              />
              <check-outlined class="editable-cell-icon-check" @click="save(record.key)" />
            </div>
            <div v-else class="editable-cell-text-wrapper">
              {{ text || ' ' }}
              <edit-outlined class="editable-cell-icon" @click="edit(record.key)" />
            </div>
          </div>
        </template>
        <template v-else-if="column.key === 'action'">
          <a-popconfirm title="你确定要删除吗?" @confirm="doDelete(record.id)">
            <a-button danger>删除</a-button>
          </a-popconfirm>
          <!--          <a-button danger @click="doDelete(record.id)">删除</a-button>-->
        </template>
      </template>
    </a-table>
  </div>
</template>

<script lang="ts" setup>
import { SmileOutlined, DownOutlined, CheckOutlined, EditOutlined } from '@ant-design/icons-vue'
import { computed, onMounted, reactive, ref, type UnwrapRef } from 'vue'
import {
  deleteUserUsingPost,
  listUserVoByPageUsingPost,
  updateUserUsingPost,
} from '@/api/userController.ts'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import { cloneDeep } from 'lodash-es'

interface DataItem {
  userName: string
}

const columns = [
  {
    title: 'id',
    dataIndex: 'id',
  },
  {
    title: '账号',
    dataIndex: 'userAccount',
  },
  {
    title: '用户名',
    dataIndex: 'userName',
  },
  {
    title: '头像',
    dataIndex: 'userAvatar',
  },
  {
    title: '简介',
    dataIndex: 'userProfile',
  },
  {
    title: '用户角色',
    dataIndex: 'userRole',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
  },
  {
    title: '操作',
    key: 'action',
  },
]

const dataList = ref<API.UserVO[]>([])
const total = ref(0)
const searchParams = reactive<API.UserQueryRequest>({
  current: 1,
  pageSize: 10,
  sortField: 'createTime',
  sortOrder: 'ascend',
})

const fetchData = async () => {
  try {
    const res = await listUserVoByPageUsingPost({
      ...searchParams,
    })
    if (res.data.code === 0 && res.data.data) {
      dataList.value = res.data.data.records.map((item) => ({ ...item, key: item.id }))
      total.value = res.data.data.total ?? 0
    } else {
      message.error('获取数据失败: ' + res.data.message)
    }
  } catch (error) {
    message.error('请求失败: ' + error)
  }
}

const editableData: UnwrapRef<Record<string, DataItem>> = reactive({})

const edit = (key: string) => {
  const record = dataList.value.find((item) => item.key === key)
  if (record) {
    editableData[key] = cloneDeep(record)
  }
}
const save = async (key: string) => {
  const record = dataList.value.find((item) => item.key === key)
  if (record) {
    Object.assign(record, editableData[key])
    const res = await updateUserUsingPost(record)
    //注册成功，跳转登录页面
    if (res.data.code === 0) {
      delete editableData[key]
      fetchData()
    } else {
      message.error('修改失败: ' + res.data.message)
    }
  }
}

const formRef=ref()
// 重置搜索栏

const resetSearch = () => {
  formRef.value.resetFields()
  doSearch()
}

onMounted(() => {
  fetchData()
})

const pagination = computed(() => {
  return {
    current: searchParams.current,
    pageSize: searchParams.pageSize,
    total: +total.value,
    showSizeChanger: true,
    showTotal: (total: number) => `共${total}条`,
  }
})

const doTableChange = (page: any) => {
  searchParams.current = page.current
  searchParams.pageSize = page.pageSize
  fetchData()
}

const doSearch = () => {
  searchParams.current = 1
  fetchData()
}

const doDelete = async (id: string) => {
  if (!id) {
    return
  }
  try {

    const res = await deleteUserUsingPost({ id })
    searchParams.current =
      total.value % searchParams.pageSize == 1
        ? searchParams.current - 1
        : searchParams.current
    if (res.data.code === 0) {
      message.success('删除成功')
      fetchData()
    } else {
      message.error('删除失败: ' + res.data.message)
    }
  } catch (error) {
    message.error('请求失败: ' + error)
  }
}
</script>

<style lang="less" scoped>
.editable-cell {
  position: relative;

  .editable-cell-input-wrapper,
  .editable-cell-text-wrapper {
    padding-right: 24px;
  }

  .editable-cell-text-wrapper {
    padding: 5px 24px 5px 5px;
  }

  .editable-cell-icon,
  .editable-cell-icon-check {
    position: absolute;
    right: 0;
    width: 20px;
    cursor: pointer;
  }

  .editable-cell-icon {
    margin-top: 4px;
    display: none;
  }

  .editable-cell-icon-check {
    line-height: 28px;
  }

  .editable-cell-icon:hover,
  .editable-cell-icon-check:hover {
    color: #108ee9;
  }

  .editable-add-btn {
    margin-bottom: 8px;
  }
}

.editable-cell:hover .editable-cell-icon {
  display: inline-block;
}
</style>
